﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using SoccerEvaluator.Common;
using SoccerEvaluator.Business;

namespace SoccerEvaluator
{
    /// <summary>
    /// 
    /// </summary>
    public class XMLLoader
    {
        /// <summary>
        /// 
        /// </summary>
        private int _totalRows;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <param name="index"></param>
        public delegate void OnMessageHandler(string message, int index);
        /// <summary>
        /// 
        /// </summary>
        public event OnMessageHandler OnMessage;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="list"></param>
        public delegate void OnTerminateHandler(List<TemplateInfo> list);
        /// <summary>
        /// 
        /// </summary>
        public event OnTerminateHandler OnTerminate;
        /// <summary>
        /// 
        /// </summary>
        private string _folder;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="folder"></param>
        public XMLLoader(string folder, int totalRows)
        {
            _totalRows = totalRows;
            _folder = folder;
        }
        /// <summary>
        /// 
        /// </summary>
        public XMLLoader()
        {

        }
        /// <summary>
        /// 
        /// </summary>
        public void Start()
        {
            string[] files = Directory.GetFiles(_folder, "*.xml");

            List<TemplateInfo> list = new List<TemplateInfo>();

            TemplateInfo rInfo = null;
            int i = 0;
            foreach (string f in files)
            {
                int pos = f.LastIndexOf(@"\") + 1;

                string fileName = f.Substring(pos);

                if (OnMessage != null)
                {
                    OnMessage("Procesando " + fileName, i);
                }

                rInfo = new TemplateInfo();

                rInfo.Scores = GetData(f);

                rInfo.User = fileName;
                rInfo.Logo = f;
                rInfo.CatchScore = 0;
                rInfo.ExactScore = 0;
                rInfo.Total = 0;

                list.Add(rInfo);

                i++;
            }

            //Notifica que termino
            OnTerminate(list);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="f"></param>
        /// <returns></returns>
        public List<ScoreInfo> GetData(string path)
        {
            List<ScoreInfo> results = new List<ScoreInfo>();

            XmlDocument doc = new XmlDocument();
            doc.Load(path);

            XmlNodeList nodes = doc.SelectNodes("/ArrayOfScoreInfo/ScoreInfo");

            ScoreInfo s = null;


            foreach (XmlNode n in nodes)
            {
                s = new ScoreInfo();

                s.Location = n.Attributes["Location"].Value;

                s.Local = n.Attributes["Local"].Value;
                s.LocalGoals = int.Parse(n.Attributes["LocalGoals"].Value);
                s.Visitor = n.Attributes["Visitor"].Value;
                s.VisitorGoals = int.Parse(n.Attributes["VisitorGoals"].Value);

                results.Add(s);
            }

            return results;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public TemplateInfo LoadResult(int templateId)
        {
            Business.UserResult fMan = new Business.UserResult();

            Business.tem

            TemplateInfo result = null;

            if (fMan.Exists(templateId))
            {
                result = new TemplateInfo();

                string fileName = fMan.GetName(path);

                result.RegisterDate = fMan.GetDate(path);

                //Carga el documento xml
                XmlDocument doc = new XmlDocument();

                Stream data = fMan.GetFile(path);

                doc.Load(data);

                XmlNode headerData = doc.SelectSingleNode("/ResultInfo");

                //Obtiene el resultado a partir de los atributos
                result = Factory.CreateResultInfo(headerData.Attributes);

                result.Name = fileName.Replace(".xml", "");

                ScoreInfo s = null;

                XmlNodeList nodes = doc.SelectNodes("/ResultInfo/Scores/ScoreInfo");

                List<ScoreInfo> scores = new List<ScoreInfo>();

                foreach (XmlNode n in nodes)
                {
                    s = Factory.CreateScoreInfo(n.Attributes);

                    scores.Add(s);
                }

                result.Scores = scores;



                //Determina el modo del proyecto en base a las fechas de los partidos
                result.ProjectMode = ValidateMode(result);


                data.Close();

            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public ProviderInfo LoadProvider(string path) 
        {
            Business.UserResult fMan = new Business.UserResult();

            ProviderInfo result = null;

            if (fMan.Exists(path))
            {
                result = new ProviderInfo();

                string fileName = fMan.GetName(path);                

                //Carga el documento xml
                XmlDocument doc = new XmlDocument();

                Stream data = fMan.GetFile(path);

                doc.Load(data);

                XmlNode headerData = doc.SelectSingleNode("/ProviderInfo");

                //Obtiene el resultado a partir de los atributos
                result = Factory.CreateProviderInfo(headerData.Attributes);

                result.Name = fileName.Replace(".xml", "");

                data.Close();

            }
            return result;
        }
        /// <summary>
        /// Determina si el proyecto ya debe cerrarse para empezar a evaluar
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private int ValidateMode(TemplateInfo result)
        {
            //La politica es que si hay un partido que ya empezo ya no se pueden ingresar mas resultados
            //por defecto es cero si no hay ningun partido que lo bloquee
            int value = 0;

            if (result.Scores != null && result.Scores.Count > 0)
            {
                DateTime now = DateTime.Now.AddHours(-1);

                TimeSpan ts;

                foreach (ScoreInfo s in result.Scores)
                {
                    ts = now - s.Date;

                    //Si queda menos de una hora bloquea
                    if (ts.TotalHours >= 0)
                    {
                        value = 1;

                        break;
                    }
                }
            }

            return value;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p"></param>
        /// <param name="userPath"></param>
        /// <returns></returns>
        public List<TemplateInfo> GetUserResults(string projectNameFile, string pathDirectory)
        {
            UserResult fMan = new UserResult();

            List<TemplateInfo> list = new List<TemplateInfo>();

            string[] files = fMan.GetFiles(pathDirectory, "xml");

            foreach (string f in files)
            {
                FileInfo fInfo = new FileInfo(f);

                if (fInfo.Name.Replace(".xml", "") != projectNameFile)
                {
                    TemplateInfo r = LoadResult(f);

                    list.Add(r);
                }
            }

            return list;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pathFile"></param>
        /// <param name="result"></param>
        public void SaveResult(string pathFile, string name, TemplateInfo result)
        {
            UserResult fMan = new UserResult();

            if (fMan.Exists(pathFile))
            {
                fMan.Delete(pathFile);
            }

            //XmlSerializer ser = new XmlSerializer(typeof(ResultInfo));

            //MemoryStream mem = new MemoryStream();

            //XmlTextWriter sw = new XmlTextWriter(mem, Encoding.UTF8);

            //ser.Serialize(sw, result);

            //sw.Close();

            fMan.AddResult(pathFile, name, result, "xml");

        }
    }
}
